package com.lmabbe.common.datasources.handle;

import cn.hutool.core.util.ReflectUtil;
import com.baomidou.dynamic.datasource.support.DdConstants;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.gitee.sunchenbin.mybatis.actable.manager.system.SysMysqlCreateTableManager;
import com.gitee.sunchenbin.mybatis.actable.manager.util.ConfigurationUtil;
import com.lmabbe.common.global.context.TenantBuildContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 同步数据库结构
 *
 * @author lmabbe
 */
@Slf4j
public class SyncDdlHandle extends InitApplicationHandle {

    public SyncDdlHandle(ApplicationContext applicationContext, TenantBuildContext tenantContext) {
        super(applicationContext, tenantContext);
    }

    @Override
    public void handle(InitApplicationContext context) {
        log.info(">>>>>>>>>>>>开始同步数据库结构>>>>>>>>>>");
        List<String> databaseIds = context.getDatabaseIds().stream()
                .filter(s -> s.contains(DdConstants.MASTER))
                .collect(Collectors.toList());
        for (String databaseId : databaseIds) {
            DynamicDataSourceContextHolder.push(databaseId);
            ConfigurationUtil bean = applicationContext.getBean(ConfigurationUtil.class);
            ReflectUtil.setFieldValue(bean, "tableAuto", "update");
            SysMysqlCreateTableManager sysMysqlCreateTableManager = applicationContext.getBean(SysMysqlCreateTableManager.class);
            sysMysqlCreateTableManager.createMysqlTable();
        }

    }
}
